﻿
/** 
* Creates an automatically looping video. 
* @author Devon O. 
* @version 0.1 
*/  
 
package com.onebyonedesign.extras {  

 	import flash.media.Video; 
	import flash.net.NetConnection; 
	import flash.net.NetStream; 
	import flash.events.NetStatusEvent; 
	import flash.events.AsyncErrorEvent;   
	
	import flash.external.ExternalInterface;

	public class VideoLoop extends Video {  

		private var URL:String;
		private var connection:NetConnection;
		private var stream:NetStream;
		private var playedOnce:Boolean = false;
		public var isPlaying:Boolean = true;
		public var requiredCp:String;
		private var firstplay:Boolean = true;
		/** 
		 * 
		 * @param	relative or absolute path to .flv file 
		 */ 
		
		public function VideoLoop(videoPath:String):void { 
			
			URL = videoPath;  
			connection = new NetConnection(); 
            
			connection.addEventListener(NetStatusEvent.NET_STATUS, onStatus); 
            connection.connect(null); 
			var customClient:Object = new Object();
			customClient.onCuePoint = onCuePoint;
			stream.client = customClient;
			
		}  
		
		public function play():void { 
			stream.resume(); 
		}  
 
		public function pause():void { 
			stream.pause(); 
		}
		
		private function onCuePoint( info:Object):void {
			
			
			var infoname:String = info.name;
			
			if (firstplay == true) {
				stream.pause(); firstplay = false;
				}
			
			
			if(requiredCp == infoname){
			stream.pause();
			isPlaying = !isPlaying;
			sendpause(infoname);
			}
		} 
		private function onStatus(nse:NetStatusEvent):void { 
			if (nse.info.code == "NetConnection.Connect.Success" && !playedOnce){ 
				playedOnce = true; 
				initVideo(); 
			} 
			if (nse.info.code == "NetStream.Play.Stop" && playedOnce) { 
				stream.seek(0); 
			}
		}  
 
		private function asyncErrorHandler(event:AsyncErrorEvent):void { 
            dispatchEvent(event); 
        }  
 
		private function initVideo():void { 
			stream = new NetStream(connection); 
			stream.addEventListener(NetStatusEvent.NET_STATUS, onStatus); 
			stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); 
            attachNetStream(stream); 
            stream.play(URL); 
		}
		
		private function sendpause(infoname):void {
            if (ExternalInterface.available) {
                ExternalInterface.call("sendToJavaScript", infoname);
            }
        }
	}
}